package com.itheima.service.impl;

import cn.hutool.core.lang.UUID;
import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MenuMapper;
import com.itheima.pojo.Menu;
import com.itheima.pojo.MenuSet;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @description:
 * @author: dalao
 * @date: 2020/4/17-11:11
 * @Version: 1.0.0
 */
@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Override
    public List<Menu> getAllMenu() {
//        先查询一级菜单
        List<Menu> menus =  menuMapper.getLevel1Menu();
//        遍历菜单,根据菜单ID查询子菜单集合
        for (Menu menu : menus) {
            List<Menu> childMenus = menuMapper.getChildMenu(menu.getId());
            menu.setChildren(childMenus);
        }
        return menus;

    }

    @Override
    public List<MenuSet> getAllMenuSet() {
        //        先查询一级菜单
        List<MenuSet> menus =  menuMapper.getLevel1MenuSet();
//        遍历菜单,根据菜单ID查询子菜单集合
        for (MenuSet menu : menus) {
            List<MenuSet> childMenus = menuMapper.getChildMenuSet(menu.getId());
            menu.setChildren(childMenus);
        }
        return menus;
    }

    @Override
    public void addMenu(Menu menu) {
        String path = UUID.randomUUID().toString();
        menu.setPath(path);
        menuMapper.addMenu(menu);
    }

    @Override
    public void deleteMenu(Integer menuId) {
//        如果删除的是一级菜单,需要先把二级菜单删掉
//        首先根据ID查询菜单
        List<Menu> childMenu = menuMapper.getChildMenu(menuId);
//        如果不为空,说明是父级菜单
        if(childMenu.size()>0){
            menuMapper.deleteChildMenu(menuId);
            menuMapper.deleteMenu(menuId);
        }else {
            menuMapper.deleteMenu(menuId);
        }
    }

    @Override
    public void addOneLevelMenu(Menu menu) {
        menuMapper.addOneLevelMenu(menu);
    }
}
